<template>
  <view class="content pb-50" style="padding-top: 70rpx;">
    <view style="margin-top: 140rpx;" v-show="tabState"></view>
    <view class="position-block">
      <view class="top-block pt-30 pb-20">
        <view class="date-block ml-20">排查周期：{{detail.checkPeriod == 1 ? '1日' : detail.checkPeriod == 2 ? '1周' : detail.checkPeriod == 3 ? '1月' : detail.checkPeriod == 4 ? '6月' : '12月'}}一次</view>
        <view class="date-block mr-20">剩余时间：{{detail.endDate}}</view>
      </view>
      <view v-show="tabState" class="tab-block pb-10">
        <u-tabs :list="tabList" :scrollable="false" :activeStyle="{ color: '#3C9CFF', fontSize: '28rpx' }" :inactiveStyle="{ fontSize: '28rpx' }" @click="tabClick"></u-tabs>
      </view>
    </view>
    <view v-if="JSON.stringify(list) != '[]'" class="list-block pl-20 pr-20">
		<view class="item-block mt-20" v-for="(item, index) in list" :key="index">
			<view class="body-block border-b-common pb-10">
        <view class="body-item pt-20 pb-25">
          <view class="item-label">危险源名称：</view>
          <view class="item-value">{{item.operationSteps ? item.operationSteps : '-'}}</view>
			  </view>
			  <view class="body-item pt-20 pb-25">
          <view class="item-label">风险点名称：</view>
          <view class="item-value">{{item.riskPoint ? item.riskPoint : '-'}}</view>
			  </view>
			  <view class="body-item pt-20 pb-25">
				<view class="item-label">危险源/潜在事件：</view>
				<view class="item-value">{{item.hazardSource ? item.hazardSource : '-'}}</view>
			  </view>
			  <!-- <view class="body-item pt-20 pb-25">
          <view class="item-label">管控措施：</view>
          <view class="item-value">
            <view>{{item.gcjsMeasures ? item.gcjsMeasures : '-'}}</view>
          </view>
			  </view> -->
			</view>
			<view class="footer-block pt-20">
			  <view class="button-block">
        <u-button  class="button" type="warning" :customStyle="{width: '120rpx', height: '50rpx', margin: '0 20rpx'}" text="管控措施" @click="openPopup1(item)"></u-button>
				<u-button v-if="params.isRegister" class="button" type="success" :customStyle="{width: '120rpx', height: '50rpx', margin: '0 20rpx'}" text="正常" @click="openPopup(item)"></u-button>
				<u-button v-if="params.isRegister" class="button" type="primary" :customStyle="{width: '120rpx', height: '50rpx', margin: '0 20rpx'}" text="登记" @click="routeToCreate(item.id, item.planExeId, item.planId, item.riskPoint,item.riskId, detail.checkType, detail.htCategory)"></u-button>

				<view v-else>
				  <u-button  v-if="item.riskState == '0'" class="button" type="success" :customStyle="{width: '120rpx', height: '50rpx', margin: '0 20rpx'}" text="正常" @click="openImagePopup(item.planDetailExeId)"></u-button>
				  <u-button  v-else class="button" type="warning" :customStyle="{width: '120rpx', height: '50rpx', margin: '0 20rpx'}" text="隐患"></u-button>
				</view>
			  </view>
			</view>
		</view>
    </view>
    <view v-else class="empty-block">
      <u-empty text="暂无数据" mode="data" icon-size="80"></u-empty>
    </view>
    <u-popup :show="popupState" mode="center" round="6rpx" @close="popupClose">
      <view class="popup-block">
        <view class="popup-title mb-30">上传文件</view>
        <u-upload :action="action" multiple :max-count="3" :capture="['camera']" :file-list="fileList" @afterRead="afterRead" @delete="deleteImage"></u-upload>
        <view class="button-block mt-50">
          <u-button type="info" text="取消" :custom-style="{width: '250rpx', backgroundColor: '#FFFFFF !important'}" @click="popupClose()"></u-button>
          <u-button type="primary" text="提交" :custom-style="{width: '250rpx'}" @click="submit"></u-button>
        </view>
      </view>
    </u-popup>
    <u-popup :show="Tips" mode="center" round="6rpx" @close="TipspopupClose">
      <view class="popup-block">
        <view style="    text-align: center;">
          <text>当前管控措施无需拍照</text>
        </view>
        <view class="button-block mt-50">
          <u-button type="info" text="取消" :custom-style="{width: '250rpx', backgroundColor: '#FFFFFF !important'}" @click="TipspopupClose()"></u-button>
          <u-button type="primary" text="提交" :custom-style="{width: '250rpx'}" @click="submits"></u-button>
        </view>
      </view>
    </u-popup>
    <u-popup :show="imageState" mode="center" round="6rpx" @close="imagePopupClose">
      <view class="popup-block">
        <view class="image-list">
          <image class="item-image" mode="aspectFill" v-for="(item, index) in imageList" :key="index" :src="item.url" @click="previewImage(item.url)"></image>
        </view>
      </view>
    </u-popup>
    <u-popup :show="controls" mode="center" round="6rpx" @close="controlsClose">
      <view class="popup-block">
        <u-collapse accordion>
          <u-collapse-item title="工程技术">
            <text class="u-collapse-content">{{gcjsMeasures ? gcjsMeasures : '-'}}</text>
          </u-collapse-item>

          <u-collapse-item title="管控措施">
            <text class="u-collapse-content">{{glcsMeasures ? glcsMeasures : '-'}}</text>
          </u-collapse-item>

          <u-collapse-item title="培训教育">
            <text class="u-collapse-content">{{pxjyMeasures ? pxjyMeasures : '-'}}</text>
          </u-collapse-item>

          <u-collapse-item title="个体防护">
            <text class="u-collapse-content">{{gtfhMeasures ? gtfhMeasures : '-'}}</text>
          </u-collapse-item>

          <u-collapse-item title="应急管理">
            <text class="u-collapse-content">{{yjglMeasures ? yjglMeasures : '-'}}</text>
          </u-collapse-item>
        </u-collapse>
        <!-- <view class="body-item pt-20 pb-25">
          <view class="item-label">工程技术：</view>
          <view class="item-value">
            <view>{{gcjsMeasures ? gcjsMeasures : '-'}}</view>
          </view>
			  </view>
        <view class="body-item pt-20 pb-25">
          <view class="item-label">管控措施：</view>
          <view class="item-value">
            <view>{{glcsMeasures ? glcsMeasures : '-'}}</view>
          </view>
			  </view>
        <view class="body-item pt-20 pb-25">
          <view class="item-label">培训教育：</view>
          <view class="item-value">
            <view>{{pxjyMeasures ? pxjyMeasures : '-'}}</view>
          </view>
			  </view>
        <view class="body-item pt-20 pb-25">
          <view class="item-label">个体防护：</view>
          <view class="item-value">
            <view>{{ gtfhMeasures ?  gtfhMeasures : '-'}}</view>
          </view>
			  </view>
        <view class="body-item pt-20 pb-25">
          <view class="item-label">应急管理:</view>
          <view class="item-value">
            <view>{{yjglMeasures ? yjglMeasures : '-'}}</view>
          </view>
			  </view> -->
        </view>
        <view >
          <u-button type="primary" text="取消" :custom-style="{width: '250rpx',}" @click="controlsClose()"></u-button>
          <!-- <u-button type="primary" text="提交" :custom-style="{width: '250rpx'}" @click="submits"></u-button> -->
        </view>
    </u-popup>
  </view>
</template>

<script>
  import { getCheckTaskDetailApi, getCheckTaskDetailListApi, updateCheckTaskInfoApi, getCheckImageListApi } from '@/apis/danger/index.js'
  import { getToken } from '@/utils/auth.js'
  import dayjs from 'dayjs'
  
  export default {
    data() {
      return {
        gcjsMeasures:'',
        glcsMeasures:'',
        pxjyMeasures:'',
        gtfhMeasures:'',
        yjglMeasures:'',
        controls:false,
        tabState: true,
        tabList: [
          { name: '待排查', isRegister: true },
          { name: '已排查', isRegister: false },
        ],
        showState: false,
        popupState: false,
        Tips:false,
        imageState: false,
        detail: {},
        list: [],
        imageList: [],
        params: {
          isRegister: true,
          pageNo: 1,
          pageSize: 10
        },
        newParams: {
          ossImg: []
        },
        action: this.uploadImageUrl,
        nowDateTime: dayjs().valueOf(),
        fileList: [],
        ossParams: {
          planId: '',
          planExeId: '',
          planDetailId: '',
          riskState: 0
        },
      }
    },
    onPullDownRefresh() {
      this.getCheckTaskDetailList(Object.assign(this.params, {pageNo: 1, pageSize: 10}))
    },
    onReachBottom() {
      if(this.pushState) this.getCheckTaskDetailList(Object.assign(this.params, {pageNo: this.params.pageNo + 1}), false)
    },
    onLoad(options) {
      console.log(options)
      wx.setNavigationBarTitle({
        title: options.type == '1' ? '排查记录' : '新增记录'
      })
      if(options.checkPeriod && options.endDate) Object.assign(this.detail, {checkPeriod: options.checkPeriod, endDate: options.endDate})
      console.log('detail', this.detail)
      if(options.planId && options.planExeId) {
        Object.assign(this.params, {planId: options.planId, planExeId: options.planExeId})
        if(options.state == 1) {
          this.tabState = false
          Object.assign(this.params, {isRegister: false})
        }
        this.getCheckTaskDetailList(this.params)
      }
    },
    onShow() {
      this.getCheckTaskDetailList(Object.assign(this.params, {pageNo: 1}))
    },
    methods: {
      // getCheckTaskDetail: function(params, planExeId) {
      //   getCheckTaskDetailApi(params).then(res => {
      //     this.getCheckTaskDetailList(Object.assign(this.params, {planId: res.id, planExeId}))
      //     this.detail = res
      //     this.showState = true
      //   }).catch(err => console.warn(err))
      // },
      getCheckTaskDetailList: function(params, freshState = true) {
        getCheckTaskDetailListApi(params).then(res => {
          if(freshState) {
            this.pushState = true
            this.list = res.list
          } else {
            this.list = this.list.concat(res.list)
          }
          if(res.list.length < this.params.pageSize) this.pushState = false
          uni.stopPullDownRefresh()
        })
      },
      openPopup1(item) {
        console.log('1111111111')
        console.log(item)
        this.gcjsMeasures = item.gcjsMeasures
        this.glcsMeasures = item.glcsMeasures
        this.pxjyMeasures = item.pxjyMeasures
        this.gtfhMeasures = item.gtfhMeasures
        this.yjglMeasures = item.yjglMeasures
       this.controls = true
      },
      openPopup: function(item) {
        Object.assign(this.ossParams, { planId: item.planId, planExeId: item.planExeId, planDetailId: item.id })
        if(item.isTakePic){
          this.popupState = true
        }else{
          this.Tips = true
        }
      },
      openImagePopup: function(id) {
        getCheckImageListApi({ id }).then(res => {
          console.log('res', res)
          if(res.ossImg && res.ossImg.length > 0) {
            this.imageList = res.ossImg
            this.imageState = true
          } else {
            uni.showToast({ title: '当前管控措施无需拍照', icon: 'none' })
          }
        }).catch(err => console.warn(err))
      },
      previewImage: function(url) {
		  console.log(url);	
        uni.previewImage({
          urls: [url],
          fail: () => {
            uni.showToast({ title: '图片加载失败', icon: 'none' })
          }
        })
      },
      tabClick: function(item) {
        this.list = []
        if(item.isRegister) {
          Object.assign(this.params, { isRegister: true})
        } else {
          Object.assign(this.params, { isRegister: false})
        }
        this.getCheckTaskDetailList(Object.assign(this.params, { pageNo: 1 }))
      },
      submits(){
        updateCheckTaskInfoApi(this.ossParams).then(res => {
          this.Tips = false
          uni.showToast({ title: '提交成功', icon: 'none' })
          this.newParams.ossImg = []
          delete this.ossParams.ossImg
          this.fileList = []
          this.getCheckTaskDetailList(Object.assign(this.params, {pageNo: 1}))
        }).catch(err => console.warn(err))
      },
      submit: function() {
        if(!this.newParams.ossImg || this.newParams.ossImg.length <= 0) {
          uni.showToast({ title: '请上传文件', icon: 'none' })
          return false
        }
        Object.assign(this.ossParams, { ossImg:  this.newParams.ossImg })
        updateCheckTaskInfoApi(this.ossParams).then(res => {
          this.popupState = false
          uni.showToast({ title: '提交成功', icon: 'none' })
		  this.newParams.ossImg = []
		  delete this.ossParams.ossImg
          this.fileList = []
          this.getCheckTaskDetailList(Object.assign(this.params, {pageNo: 1}))
        }).catch(err => console.warn(err))
      },
      async afterRead(event) {
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = [].concat(event.file)
        let fileListLen = this.fileList.length
        lists.map((item) => {
          this.fileList.push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          let item = this.fileList[fileListLen]
          if(result.status == 'success') {
            this.fileList.splice(fileListLen, 1, Object.assign(item, {
              status: result.status,
              message: '',
              url: result.url
            }))
            fileListLen++
          } else {
            this.fileList.splice(fileListLen, 1)
          }
        }
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: this.uploadImageUrl,
            filePath: url,
            name: 'file',
            formData: {
              user: 'test'
            },
            header: {
              'Authorization': `Bearer ${getToken()}`,
              'tenant-id':  '1'
            },
            success: (res) => {
              let result = JSON.parse(res.data)
              if (result.code == 0) {
                this.newParams.ossImg.push(result.data)
                resolve({url: result.data.url, status: 'success'})
              } else {
                uni.showToast({ title: 'OSS服务器错误', icon: 'none' })
                resolve({url, status: 'fail'})
              }
            },
            fail: () => uni.showToast({ title: '图片上传失败', icon: 'none' })
          })
        })
      },
      deleteImage: function(event) {
        this.newParams.ossImg.splice(event.index, 1)
        this.fileList.splice(event.index, 1)
      },
      getRemainingTime: function(startTime = dayjs().format('YYYY-MM-DD HH:mm:ss'), endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')) {
        console.log('startTime', startTime)
        console.log('endTime', endTime)
        return startTime && endTime && (dayjs(startTime).valueOf() < dayjs(endTime).valueOf()) ? dayjs(endTime).diff(startTime, 'hour') : 0
      },
      popupClose: function() {
		this.newParams.ossImg = []
        this.fileList = []
        this.popupState = false
      },
      TipspopupClose(){
        this.Tips = false
      },
      controlsClose(){
        this.controls = false
      },
      imagePopupClose: function() {
        this.imageList = []
        this.imageState = false
      },
      routeToCreate: function(planDetailId, planExeId, planId,riskPoint,riskId,checkType, htCategory,) {
        uni.navigateTo({ url: `/pagesDanger/checkTaskCreate?planDetailId=${planDetailId}&planExeId=${planExeId}&planId=${planId}&checkType=${checkType}&category=${htCategory}&riskPoint=${riskPoint}&riskId=${riskId}` })
      }
    }
  }
</script>

<style>
  page {
    background-color: #F4F4F4;
  }
  .u-upload__wrap__preview__image {
    width: 160rpx !important;
    height: 160rpx !important;
  }
</style>

<style lang="scss" scoped>
  .border-b-common { 
    border-bottom: 1rpx solid #F4F4F4; 
  }
  .content {
    .position-block {
      background-color: #FFFFFF;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      z-index: 99;
      .top-block {
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-shadow: 0 0 10rpx 0 #F4F4F4;
        .date-block {
          font-size: 28rpx;
          line-height: 40rpx;
          font-weight: 500;
          color: #333333;
        }
      }
    }
    .list-block {
      .item-block {
        background-color: #FFFFFF;
        border-radius: 6rpx;
        box-shadow: 0 0 10rpx 0 #F4F4F4;
        padding: 25rpx;
        margin-top: 25rpx;
        .header-block {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .date-block {
            width: 260rpx;
            font-size: 24rpx;
            line-height: 32rpx;
            color: #333333;
          }
        }
        .body-block {
          .body-item {
            font-size: 28rpx;
            line-height: 40rpx;
            color: #666666;
            display: flex;
            .item-label {
              min-width: 170rpx;
            }
          }
        }
        .footer-block {
          @extend .header-block;
          align-items: flex-end;
        }
        .button-block {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: flex-end;
          .button {
            width: 100rpx;
          }
        }
      }
    }
    .empty-block {
      padding-top: 300rpx;
    }
    .popup-block {
      width: 600rpx;
      padding: 20rpx;
      .image-list {
        display: flex;
        flex-wrap: wrap;
        .item-image {
          width: 180rpx;
          height: 180rpx;
          border-radius: 10rpx;
          background-color: #CCCCCC;
          margin: 10rpx;
        }
      }
      .popup-title {
        font-size: 30rpx;
        line-height: 42rpx;
        font-weight: 500;
        text-align: center;
      }
      .button-block {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
  }
</style>
